import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginApi } from '@/api/user'
import type { LoginParams, LoginApi } from '@/types/data'
import { ElMessage } from 'element-plus'

const useUserStore = defineStore(
  'user',
  () => {
    // 用户信息
    const userInfo = ref({} as LoginApi)

    // 登录获取用户信息
    const login = async (data: LoginParams) => {
      const res = await loginApi(data)

      if (res.data.state === 200) {
        userInfo.value = res.data.data
      } else {
        ElMessage.error(res.data.msg)
        return Promise.reject('登录失败') //失败的Promise实例
      }
    }
    // 退出清空用户信息
    const logout = () => {
      userInfo.value = {} as LoginApi
    }

    return { userInfo, login, logout }
  },
  {
    persist: true,
  },
)

export default useUserStore
